package edge

import (
	"encoding/json"
	"iot-base/auth/api/crontab"
	"iot-base/auth/model"
	"iot-base/auth/svc"
	types2 "iot-base/auth/types"
	"time"
)

// AddEdgeTask 添加任务
func AddEdgeTask(params []byte) ([]byte, error) {
	var task model.Tasks
	err := json.Unmarshal(params, &task)
	if err != nil {
		return nil, err
	}
	err = svc.Dao.TTasks.Add(&task)
	if err != nil {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	if task.Switch == "enable" {
		// 添加定时任务.
		execTime, _ := time.ParseInLocation("15:04:05", task.ExecTime, time.Local)
		_ = crontab.Cron.AddTask(task.CodeId, task.TimeType, execTime, task.Day)
	}
	return nil, nil
}

// DelEdgeTask 删除任务.
func DelEdgeTask(params []byte) ([]byte, error) {
	var req types2.ReqDelTaskByCodeId
	err := json.Unmarshal(params, &req)
	if err != nil {
		return nil, err
	}
	err = svc.Dao.TTasks.DeleteByCodeId(req.CodeId)
	if err != nil {
		return nil, err
	}
	// 移除定时任务.
	crontab.Cron.RemoveTask(req.CodeId)
	return nil, nil
}

// ModifyEdgeTask 修改任务
func ModifyEdgeTask(params []byte) ([]byte, error) {
	var req model.Tasks
	err := json.Unmarshal(params, &req)
	if err != nil {
		return nil, err
	}
	req.ID = 0
	err = svc.Dao.TTasks.UpdateByCodeId(req.CodeId, req)
	if err != nil {
		return nil, err
	}
	// 添加定时任务.
	crontab.Cron.RemoveTask(req.CodeId)
	if req.TaskType == types2.ZeroDriftAndSpanDrift {
		crontab.Cron.RemoveSubTask(req.RunTaskLogId)
	}
	if req.Switch != "disable" {
		// 禁用之后不用，更新任务
		execTime, _ := time.ParseInLocation("15:04:05", req.ExecTime, time.Local)
		_ = crontab.Cron.AddTask(req.CodeId, req.TimeType, execTime, req.Day)
	}
	return nil, nil
}
